package com.css.fxfzypg.modules.preassesstaskmanage.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.maps.service.TaskRegionMapService;
import com.css.fxfzypg.modules.preassesstaskmanage.entity.PreAssessTaskEntity;
import com.css.fxfzypg.modules.preassesstaskmanage.repository.PreAssessTaskRepository;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreAssessVo;
import com.css.fxfzypg.modules.preassesstaskmanage.vo.PreVo;
import com.css.fxfzypg.modules.resultupload.repository.entity.ResultMainEntity;
import com.css.fxfzypg.modules.surveytaskmanage.vo.TaskVo;
import com.css.fxfzypg.util.CreateGson;
import com.css.fxfzypg.util.PlatformObjectUtils;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @program
 * @description
 * @create 2022/8/8 10:45
 **/
@Repository
public class PreAssessTaskRepositoryImpl implements PreAssessTaskRepository {
    @Resource
    JdbcTemplate jdbcTemplate;

    @Resource
    NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    @Resource
    SysAreaService sysAreaService;

    @Resource
    SysRoleService sysRoleService;

    @Resource
    SUserService sUserService;

    @Resource
    TaskRegionMapService taskRegionMapService;

    @Override
    public void saveTask(PreAssessTaskEntity preAssessTaskEntity) {
        //处理空间数据，判断存在自相交则获取修复后的空间数据，否则返回原空间数据wkt
        String geomText = taskRegionMapService.getGeomValidWkt(preAssessTaskEntity.getGeom());
        preAssessTaskEntity.setGeom(geomText);
        String sql = "insert into ypg_preassess_task(id,task_year,task_num,task_name,task_area,task_region,task_manager,task_manager_id," +
                "group_name,group_leader,task_status,parent_task,del_flag,create_user,create_time,update_user,update_time," +
                "group_id,parent_id,task_district,mobile_phone,group_leader_id,report_id,assign_set_arthquake,geom) " +
                "values(:id, :taskYear, :taskNum, :taskName, :taskArea, :taskRegion, :taskManager,:taskManagerId, " +
                ":groupName, :groupLeader, :taskStatus, :parentTask, :delFlag, :createUser, :createTime, :updateUser, :updateTime, " +
                ":groupId, :parentId, :taskDistrict, :mobilePhone, :groupLeaderId, :reportId, :assignSetArthquake, " +
                "ST_GeometryFromText(:geom,4490))";
        SqlParameterSource source = new BeanPropertySqlParameterSource(preAssessTaskEntity);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void completeTask(String taskStatus, String id) {
        String sql = "update ypg_preassess_task set task_status = ? where id =?";
        jdbcTemplate.update(sql, taskStatus, id);
    }


    @Override
    public List<PreAssessTaskEntity> getSubTask(String parentTaskId) {
        String sql = "select * from ypg_preassess_task where parent_id = ? and del_flag='0'";
        List<PreAssessTaskEntity> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(PreAssessTaskEntity.class), parentTaskId);
        return list;
    }

    @Override
    public PreAssessTaskEntity findById(String taskId) {
        String sql = "select id," +
                "task_year," +
                "task_num," +
                "task_name," +
                "task_area," +
                "task_region," +
                "task_manager," +
                "group_name," +
                "group_leader," +
                "task_status," +
                "parent_task," +
                "del_flag," +
                "create_user," +
                "create_time," +
                "update_user," +
                "update_time," +
                "group_id," +
                "parent_id," +
                "task_district," +
                "mobile_phone," +
                "group_leader_id," +
                "report_id," +
                "assign_set_arthquake," +
                "st_astext(geom) geom," +
                "task_manager_id," +
                "sampling_survey_point_id from ypg_preassess_task where id = ? ";
        List<PreAssessTaskEntity> preAssessTaskEntity = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(PreAssessTaskEntity.class), taskId);
        return preAssessTaskEntity.size() == 0 ? null : preAssessTaskEntity.get(0);
    }

    @Override
    public List<PreAssessTaskEntity> findById(List<String> taskIdList) {
        String sql = "select id," +
                "task_year," +
                "task_num," +
                "task_name," +
                "task_area," +
                "task_region," +
                "task_manager," +
                "group_name," +
                "group_leader," +
                "task_status," +
                "parent_task," +
                "del_flag," +
                "create_user," +
                "create_time," +
                "update_user," +
                "update_time," +
                "group_id," +
                "parent_id," +
                "task_district," +
                "mobile_phone," +
                "group_leader_id," +
                "report_id," +
                "assign_set_arthquake," +
                "st_astext(geom) geom," +
                "task_manager_id," +
                "sampling_survey_point_id from ypg_preassess_task where id in (:taskIdList) ";
        Map idMap = new HashMap();
        idMap.put("taskIdList", taskIdList);
        return namedParameterJdbcTemplate.query(sql, idMap,new BeanPropertyRowMapper<>(PreAssessTaskEntity.class));
    }

    @Override
    public void updateTask(PreAssessTaskEntity preAssessTaskEntity) {
        String sql = "update ypg_preassess_task set task_name = :taskName, group_id= :groupId ,group_leader = :groupLeader " +
                ",group_leader_id = :groupLeaderId ,group_name = :groupName ,update_user = :updateUser ,update_time = :updateTime " +
                ",mobile_phone =:mobilePhone ,task_status = :taskStatus where id = :id";
        SqlParameterSource source = new BeanPropertySqlParameterSource(preAssessTaskEntity);
        namedParameterJdbcTemplate.update(sql, source);
    }

    @Override
    public void assignGroup(PreAssessTaskEntity preAssessTaskEntity) {
        String sql = "update ypg_preassess_task set group_id= :groupId ,group_leader = :groupLeader ,group_leader_id = :groupLeaderId ,group_name = :groupName ,update_user = :updateUser ," +
                "update_time = :updateTime ,mobile_phone =:mobilePhone ,task_status = :taskStatus where id = :id";
        SqlParameterSource source = new BeanPropertySqlParameterSource(preAssessTaskEntity);
        namedParameterJdbcTemplate.update(sql, source);
    }


    @Override
    public Map<String, Object> findParentIdByTask(String parentId, TaskVo taskVo, int curPage, int pageSize) {
        StringBuilder sql = new StringBuilder("select * from ypg_preassess_task");
        StringBuilder whereSql = new StringBuilder(" where del_flag = '0' and parent_id = '" + parentId + "'");
        StringBuilder orderSql = new StringBuilder(" order by create_time desc");
        StringBuilder countSql = new StringBuilder(" select count(*) from ypg_preassess_task");
        int firstIndex = (curPage - 1) * pageSize;
        int lastIndex = pageSize;

        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();
        if (!roles.contains(FxfzConstants.YPG_COUN_GL_ROLE) && !roles.contains(FxfzConstants.YPG_PRI_GL_ROLE)) {
            whereSql.append(" and create_user = '" + taskVo.getCreateUser() + "'");
        } else if (roles.contains(FxfzConstants.YPG_PRI_GL_ROLE) && !roles.contains(FxfzConstants.YPG_COUN_GL_ROLE)) {
            String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
            if (!PlatformObjectUtils.isEmpty(areaNameByAreaId)) {
                whereSql.append(" and task_district like '%" + areaNameByAreaId + "%'");
            }
        }

        StringBuilder limitSql = new StringBuilder(" limit " + lastIndex + " offset " + firstIndex);
        if (!PlatformObjectUtils.isEmpty(taskVo.getTaskNum())) {
            whereSql.append(" and task_num like '%" + taskVo.getTaskNum() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(taskVo.getTaskName())) {
            whereSql.append(" and task_name like '%" + taskVo.getTaskName() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(taskVo.getTaskStatus())) {
            whereSql.append(" and task_status = '" + taskVo.getTaskStatus() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(taskVo.getProvince())) {
            if (!PlatformObjectUtils.isEmpty(taskVo.getCity())) {
                if (!PlatformObjectUtils.isEmpty(taskVo.getCounty())) {
                    if (("北京市".equals(taskVo.getProvince()) || "天津市".equals(taskVo.getProvince()) || "重庆市".equals(taskVo.getProvince()) || "上海市".equals(taskVo.getProvince()))) {
                        whereSql.append(" and task_district like '%" + taskVo.getProvince() + "-" + taskVo.getCounty() + "%'");
                    } else {
                        whereSql.append(" and task_district like '%" + taskVo.getProvince() + "-" + taskVo.getCity() +
                                "-" + taskVo.getCounty() + "%'");
                    }
                } else {
                    whereSql.append(" and task_district like '%" + taskVo.getProvince() + "-" + taskVo.getCity() +
                            "%'");
                }
            } else {
                whereSql.append(" and task_district like '%" + taskVo.getProvince() + "%'");
            }
        }
        String sqlWhole = sql.append(whereSql).append(orderSql).append(limitSql).toString();
        countSql.append(whereSql);
        List<PreAssessVo> list = jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<>(PreAssessVo.class));
        Integer total = jdbcTemplate.queryForObject(countSql.toString(), Integer.class);
        Map<String, Object> map = new HashMap();
        map.put("total", total);
        map.put("rows", list);
        return map;
    }

    @Override
    public List<PreAssessVo> findSubIdByTask(String parentId, TaskVo taskVo) {
        StringBuilder sql = new StringBuilder("select * from ypg_preassess_task");
        StringBuilder whereSql = new StringBuilder(" where del_flag = '0' and parent_id = '" + parentId + "'");
        StringBuilder orderSql = new StringBuilder(" order by create_time desc");

        StringBuilder str = new StringBuilder("");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();
        if (!roles.contains(FxfzConstants.YPG_COUN_GL_ROLE) && !roles.contains(FxfzConstants.YPG_PRI_GL_ROLE)) {
            if(PlatformObjectUtils.isEmpty(taskVo.getCreateUser())){
                taskVo.setCreateUser(PlatformSessionContext.getUserID());
            }
            whereSql.append(" and create_user = '" + taskVo.getCreateUser() + "'");
        } else if (roles.contains(FxfzConstants.YPG_PRI_GL_ROLE) && !roles.contains(FxfzConstants.YPG_COUN_GL_ROLE)) {
            String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
            if (!PlatformObjectUtils.isEmpty(areaNameByAreaId)) {
                whereSql.append(" and task_district like '%" + areaNameByAreaId + "%'");
            }
        }
        if (!PlatformObjectUtils.isEmpty(taskVo.getTaskNum())) {
            whereSql.append(" and task_num like '%" + taskVo.getTaskNum() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(taskVo.getTaskName())) {
            whereSql.append(" and task_name like '%" + taskVo.getTaskName() + "%'");
        }
        if (!PlatformObjectUtils.isEmpty(taskVo.getTaskStatus())) {
            whereSql.append(" and task_status = '" + taskVo.getTaskStatus() + "'");
        }
        if (!PlatformObjectUtils.isEmpty(taskVo.getProvince()) || !PlatformObjectUtils.isEmpty(taskVo.getCity()) || !PlatformObjectUtils.isEmpty(taskVo.getCounty())) {
            whereSql.append(" and (");
            if (!PlatformObjectUtils.isEmpty(taskVo.getProvince())) {
                whereSql.append(" task_district like '%" + taskVo.getProvince() + "%'");
            }
            if (!PlatformObjectUtils.isEmpty(taskVo.getCity())) {
                whereSql.append(" or task_district like '%" + taskVo.getCity() + "%'");
            }
            if (!PlatformObjectUtils.isEmpty(taskVo.getCounty())) {
                whereSql.append(" or task_district like '%" + taskVo.getCounty() + "%'");
            }
            whereSql.append(") ");
        }
        String sqlWhole = sql.append(whereSql).append(orderSql).toString();

        List<PreAssessVo> list = jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<>(PreAssessVo.class));
        return list;
    }

    @Override
    public String getMaxParentNum(String taskYear, String divisionCode) {
        String sql = "select max(task_num) from ypg_preassess_task where  del_flag = '0' and parent_id = '0' and task_num like '%" + taskYear + "%'" +
                "and SUBSTRING (task_num, 6, 2)= '" + divisionCode + "'";
        String maxParentNum = jdbcTemplate.queryForObject(sql, String.class);
        return maxParentNum;
    }

    @Override
    public List<PreAssessTaskEntity> getAllparentTask(String parentId, String userId) {
        StringBuilder sql = new StringBuilder("select * from ypg_preassess_task");
        StringBuilder whereSql = new StringBuilder(" where del_flag = '0' ");

        StringBuilder str = new StringBuilder("");
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> roleMaps = JSONObject.parseArray(role, Map.class);
        for (Map roleMap : roleMaps) {
            str.append(roleMap.get("roleCode") + ",");
        }
        String roles = str.toString();
        if (!roles.contains(FxfzConstants.YPG_COUN_GL_ROLE) && !roles.contains(FxfzConstants.YPG_PRI_GL_ROLE)) {
            whereSql.append(" and create_user = '" + userId + "'");
        } else if (roles.contains(FxfzConstants.YPG_PRI_GL_ROLE) && !roles.contains(FxfzConstants.YPG_COUN_GL_ROLE)) {
            String areaNameByAreaId = sysAreaService.getAreaNameByAreaId(sUser.getProvinceId());
            if (!PlatformObjectUtils.isEmpty(areaNameByAreaId)) {
                whereSql.append(" and task_district like '%" + areaNameByAreaId + "%'");
            }
        }


        if (!PlatformObjectUtils.isEmpty(parentId)) {
            whereSql.append(" and parent_id = '" + parentId + "'");
        }
        String sqlWhole = sql.append(whereSql).toString();

        List<PreAssessTaskEntity> list = jdbcTemplate.query(sqlWhole, new BeanPropertyRowMapper<>(PreAssessTaskEntity.class));
        return list;
    }

    @Override
    public void insertReportId(String taskId, String reportId) {
        String sql = "update ypg_preassess_task set report_id =? where del_flag = '0' and id = ? ";
        jdbcTemplate.update(sql, reportId, taskId);
    }

    @Override
    public void assignment(String taskId) {
        String sql = "update ypg_preassess_task set assign_set_arthquake = '0' where del_flag = '" + YNEnum.N.toString() + "' and id = ? ";
        jdbcTemplate.update(sql, taskId);
    }

    @Override
    public PreAssessTaskEntity getPreAssessTaskByTaskNum(String taskNum) {
        String sql = "select * from ypg_preassess_task where task_num = ? and del_flag = '0'";
        PreAssessTaskEntity preAssessTaskEntity = null;
        try {
            preAssessTaskEntity = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(PreAssessTaskEntity.class), taskNum);
        } catch (DataAccessException e) {
            return null;
        }
        return preAssessTaskEntity;
    }

    @Override
    public PreAssessTaskEntity getPreAssessTaskByReportId(String reportId) {
        String sql = "select * from ypg_preassess_task where report_id = ? ";
        PreAssessTaskEntity preAssessTaskEntity = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(PreAssessTaskEntity.class), reportId);
        return preAssessTaskEntity;
    }

    @Override
    public boolean updateTaskStatus(String taskStatus, String reportId) {
        String sql = "update ypg_preassess_task set task_status = ? where del_flag = '" + YNEnum.N.toString() + "' and report_id = ? ";
        return jdbcTemplate.update(sql, taskStatus, reportId) > 0;
    }


    @Override
    public PreAssessTaskEntity getParentTask(String parentTaskNum) {
        String sql = "select * from ypg_preassess_task where del_flag = '0' and task_num = ? ";
        PreAssessTaskEntity preAssessTaskEntity = new PreAssessTaskEntity();
        try {
            preAssessTaskEntity = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(PreAssessTaskEntity.class), parentTaskNum);
            return preAssessTaskEntity;
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    @Override
    public String getMaxSubTaskCNum(String parentTaskNum) {
        String sql = "select max(task_num) from ypg_preassess_task where del_flag = '0' and parent_task = ?";
        String maxSubTaskCNum = jdbcTemplate.queryForObject(sql, String.class, parentTaskNum);
        return maxSubTaskCNum;
    }

    @Override
    public void deleteTask(String delFlag, String id) {
        String sql = "update ypg_preassess_task set del_flag= ? where id = ?";
        jdbcTemplate.update(sql, delFlag, id);
    }


    @Override
    public List<PreVo> getFuTask() {
        String sql = "select id,task_num,task_name,task_district from ypg_preassess_task where del_flag='0' and task_status != '3' and parent_id ='0'";
        try {
            List<PreVo> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(PreVo.class));
            return list;
        } catch (DataAccessException e) {
            return null;
        }
    }

    @Override
    public void saveSurveySamplingPoint(String samplingSurveyPointId, String id) {
        String sql = "update ypg_preassess_task set sampling_survey_point_id = ? where id =?";
        jdbcTemplate.update(sql, samplingSurveyPointId, id);
    }

    //查询部分任务信息，用于PreVo列表展示
    @Override
    public List<PreAssessTaskEntity> getTaskListByUserId(String userId) {
        String sql = "select task.id,task.task_num,task.task_name,task.task_district from ypg_preassess_task task,ypg_group_user u " +
                "where task.group_id=u.group_id and u.user_id='" + userId + "' and parent_id = '0' and task.del_flag='0'" +
                " union " +
                "(select task.id,task.task_num,task.task_name,task.task_district from ypg_preassess_task task " +
                "where (task.task_manager_id='" + userId + "' or task.group_leader_id='" + userId + "') and parent_id = '0' and task.del_flag='0')";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(PreAssessTaskEntity.class));
    }
}
